'use strict';

const {
	Controller
} = require('uni-cloud-router');
const {
	getUserInfo
} = require("user-info-admin");
const dbcmd = uniCloud.database().command;

module.exports = class GoodsController extends Controller {

	// 添加商品
	async add() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let uniIdToken = this.ctx.event.uniIdToken
		let userInfo = await getUserInfo(uniIdToken)
		let app_id = userInfo.app_id

		let {
			goods,
			detail,
			skus
		} = this.ctx.data;
		goods.app_id = app_id
		// 限时精选、热门推荐 排序
		goods.limited_sort = goods.sort;
		goods.hot_sort = goods.sort;

		// 商品基本值
		goods.name = goods.name ? goods.name + '' : '';
		goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

		// 处理商品详情前端显示UI样式
		detail.desc_mobile = detail.desc_mobile.replace(/style="max-width:100%;"/gi, '').replace(/<img src/gi,
			'<img style="max-width:100%;display:block;" src');

		// 是否填写商品分享设置
		goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
		goods.share_img = goods.share_img || goods.img;
		goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

		// 商品默认值
		const goods_id = new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0');
		goods._id = goods_id;
		goods.stock_wh_num = goods.stock_num;
		goods.create_time = new Date().getTime();
		goods.create_uid = this.ctx.auth.uid;
		goods.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		// 写入商品数据
		const goodsRes = await this.db.collection('wmzmall-goods').add(goods);

		// 商品详情默认值
		detail.goods_id = goods_id;
		detail.create_time = new Date().getTime();
		detail.create_uid = this.ctx.auth.uid;
		detail.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		// 商品SKU默认值
		skus.forEach(x => {
			x._id = goods_id + '_' + x.goods_sku;
			x.goods_id = goods_id;
			x.img = x.img || goods.img;
			x.imgObj = x.imgObj || goods.imgs[0];
			x.stock_wh_num = x.stock_num;
			x.limit = goods.limit;

			x.create_time = new Date().getTime();
			x.create_uid = this.ctx.auth.uid;
			x.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		});

		// 写入商品详情数据
		await this.db.collection('wmzmall-goods-detail').add(detail);
		if (skus.length > 0) {
			// 写入商品SKU数据
			await this.db.collection('wmzmall-goods-sku').add(skus);
		}

		response.code = 0;
		response.msg = '操作成功';

		return response;
	}
	// 验证请求数据
	validate(req) {
		if (!req) this.throw('请求参数不存在');
		if (!req.goods) this.throw('商品参数不存在');
		if (!req.detail) this.throw('商品详情参数不存在');

		if (!req.goods.name) this.throw('商品名称必填');
		if (!req.goods.cid) this.throw('请选择商品分类');
		if (req.goods.price <= 0) this.throw('商城价格不能小于0');
		if (!req.goods.img) this.throw('请上传商品主图');
	}

	// 获取商品数据
	async detail() {
		let response = {
			code: 1,
			goods: {},
			goods_detail: {},
			skus: [],
		};

		let start = new Date().getTime();
		const {
			goods_id
		} = this.ctx.data;

		// 产品数据
		let goods = await this.db.collection('wmzmall-goods').doc(goods_id).get();

		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}

		const detail = await this.db.collection('wmzmall-goods-detail')
			.where({
				goods_id: goods_id
			})
			.get();
		const skus = await this.db.collection('wmzmall-goods-sku')
			.where({
				goods_id: goods_id
			})
			.get();

		response.goods = goods.data[0];
		response.goods_detail = detail.data[0];
		response.skus = skus.data;

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 编辑商品
	async edit() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let uniIdToken = this.ctx.event.uniIdToken
		let userInfo = await getUserInfo(uniIdToken)
		let app_id = userInfo.app_id

		let {
			goods_id,
			goods,
			detail,
			skus
		} = this.ctx.data;
		try {

			// 产品数据
			let __goods = await this.db.collection('wmzmall-goods').doc(goods_id).get();

			if (!__goods || __goods.data.length <= 0) {
				response.msg = `当前产品不存在`;
				return response;
			}
			goods.app_id = app_id
			goods.level_price=goods.level_price
			// 限时精选、热门推荐 排序
			goods.limited_sort = goods.sort;
			goods.hot_sort = goods.sort;
			goods.type = __goods.data[0].type
			// 商品基本值
			goods.name = goods.name ? goods.name + '' : '';
			goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';
			// 处理商品详情前端显示UI样式
			detail.desc_mobile = detail.desc_mobile.replace(/style="max-width:100%;"/gi, '').replace(
				/<img src/gi, '<img style="max-width:100%;display:block;" src');

			// 是否填写商品分享设置
			goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
			goods.share_img = goods.share_img || goods.img;
			goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

			// 商品默认值
			goods.last_modify_uname = new Date().getTime();
			goods.last_modify_uid = this.ctx.auth.uid;
			goods.last_modify_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;

			delete goods._id;
			// 写入商品数据
			const goodsRes = await this.db.collection('wmzmall-goods').doc(goods_id).set(goods);

			// 商品详情默认值
			detail.last_modify_uname = new Date().getTime();
			detail.last_modify_uid = this.ctx.auth.uid;
			detail.last_modify_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
			// 商品SKU默认值
			skus.forEach(x => {
				x._id = goods_id + '_' + x.goods_sku;
				x.goods_id = goods_id;
				x.img = x.img || goods.img;
				x.imgObj = x.imgObj || goods.imgs[0];
				x.stock_wh_num = x.stock_num;
				x.limit = goods.limit;

				x.create_time = new Date().getTime();
				x.create_uid = this.ctx.auth.uid;
				x.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
			});

			// 写入商品详情数据
			await this.db.collection('wmzmall-goods-detail').where({
				goods_id: goods_id
			}).update(detail);

			// 删除商品SKU数据
			await this.db.collection('wmzmall-goods-sku').where({
				goods_id: goods_id
			}).remove();
			if (skus && skus.length > 0) {
				// 写入商品SKU数据
				await this.db.collection('wmzmall-goods-sku').add(skus);
			}

			response.code = 0;
			response.msg = '操作成功';

		} catch (e) {
			//TODO handle the exception
			console.log('catch', e);
		}
		return response;
	}

	// 商品分类删除
	async classifyRemove() {
		let response = {
			code: 1,
			msg: '',
			datas: null
		};

		let {
			id
		} = this.ctx.data;

		try {
			const goodsRes = await this.db.collection('wmzmall-goods').where({
				cids: id
			}).get();

			if (!goodsRes.data.length) {
				await this.db.collection('wmzmall-goods-category').doc(id).remove();
				response.msg = '操作成功';
				response.code = 0;
			} else {
				response.msg = '此分类存在商品，不可删除';
				response.code = 100;
			}
		} catch (err) {
			response.msg = err.message;
			response.code = 500;
		}

		return response;
	}

}